import React, { useState, useEffect } from 'react';
import {
  Container,
  Box,
  Typography,
  TextField,
  Button,
  Paper,
  Grid,
  styled,
  Card,
  CardContent,
  Divider,
  LinearProgress,
  Fade,
  Grow,
  Zoom,
  CircularProgress,
  Theme,
  useTheme,
  InputAdornment,
  IconButton,
  Tooltip,
  Select,
  MenuItem,
  FormControl,
  InputLabel
} from '@mui/material';

interface MatchData {
  wins: number;
  draws: number;
  losses: number;
  goalsFor: number;
  goalsAgainst: number;
}

interface TeamData {
  h2h: MatchData;
  recent: MatchData;
}

interface ThemeProps {
  theme: Theme;
}

const StyledCard = styled(Card)(({ theme }) => ({
  background: 'linear-gradient(145deg, #ffffff 0%, #f5f5f5 100%)',
  borderRadius: theme.spacing(2),
  boxShadow: '0 8px 32px rgba(0,0,0,0.1)',
  transition: 'all 0.3s ease-in-out',
  '&:hover': {
    transform: 'translateY(-4px)',
    boxShadow: '0 12px 48px rgba(0,0,0,0.15)',
  },
  animation: 'cardFloat 6s ease-in-out infinite',
  '@keyframes cardFloat': {
    '0%, 100%': {
      transform: 'translateY(0)',
    },
    '50%': {
      transform: 'translateY(-10px)',
    },
  },
}));

const StyledTextField = styled(TextField)(({ theme }) => ({
  '& .MuiOutlinedInput-root': {
    borderRadius: theme.spacing(1),
  },
  '& .MuiOutlinedInput-input': {
    padding: theme.spacing(1),
  },
}));

const AnimatedTextField = styled(StyledTextField)(({ theme }) => ({
  '& .MuiOutlinedInput-root': {
    transition: 'all 0.3s ease-in-out',
    '&:hover': {
      transform: 'scale(1.02)',
    },
    '&.Mui-focused': {
      transform: 'scale(1.02)',
      boxShadow: '0 4px 20px rgba(25, 118, 210, 0.15)',
    },
  },
}));

const DataRow = styled(Box)(({ theme }) => ({
  display: 'flex',
  gap: theme.spacing(2),
  marginBottom: theme.spacing(2),
  [theme.breakpoints.down('sm')]: {
    flexDirection: 'column',
  },
}));

const ResultCard = styled(Card)(({ theme }) => ({
  background: 'linear-gradient(135deg, #1976d2 0%, #1565c0 100%)',
  color: 'white',
  padding: theme.spacing(2),
  marginTop: theme.spacing(3),
  borderRadius: theme.spacing(2),
  position: 'relative',
  overflow: 'hidden',
  '&::before': {
    content: '""',
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    background: 'linear-gradient(45deg, transparent 0%, rgba(255,255,255,0.1) 50%, transparent 100%)',
    animation: 'shimmer 2s infinite',
  },
  '@keyframes shimmer': {
    '0%': {
      transform: 'translateX(-100%)',
    },
    '100%': {
      transform: 'translateX(100%)',
    },
  },
}));

const PulsingButton = styled(Button)(({ theme }) => ({
  animation: 'pulse 2s infinite',
  '@keyframes pulse': {
    '0%': {
      transform: 'scale(1)',
      boxShadow: '0 0 0 0 rgba(33, 150, 243, 0.4)',
    },
    '70%': {
      transform: 'scale(1.05)',
      boxShadow: '0 0 0 10px rgba(33, 150, 243, 0)',
    },
    '100%': {
      transform: 'scale(1)',
      boxShadow: '0 0 0 0 rgba(33, 150, 243, 0)',
    },
  },
}));

const HandicapTextField = styled(TextField)(({ theme }) => ({
  '& .MuiOutlinedInput-root': {
    borderRadius: theme.spacing(1),
    backgroundColor: 'rgba(255, 255, 255, 0.05)',
    transition: 'all 0.3s ease-in-out',
    '&:hover': {
      backgroundColor: 'rgba(255, 255, 255, 0.1)',
      transform: 'translateY(-2px)',
    },
    '&.Mui-focused': {
      backgroundColor: 'rgba(255, 255, 255, 0.15)',
      transform: 'translateY(-2px)',
      boxShadow: '0 4px 20px rgba(25, 118, 210, 0.25)',
    }
  },
  '& .MuiOutlinedInput-input': {
    padding: theme.spacing(1.5),
    textAlign: 'center',
    fontSize: '1.1rem',
    fontWeight: 500,
  },
  '& .MuiInputLabel-root': {
    fontSize: '0.9rem',
    fontWeight: 500,
    '&.Mui-focused': {
      color: theme.palette.primary.main,
    }
  },
  width: '150px',
}));

const HandicapContainer = styled(Box)(({ theme }) => ({
  display: 'flex',
  flexDirection: 'column',
  gap: theme.spacing(2),
  padding: theme.spacing(2),
  backgroundColor: 'rgba(25, 118, 210, 0.05)',
  borderRadius: theme.spacing(2),
  transition: 'all 0.3s ease-in-out',
  '&:hover': {
    backgroundColor: 'rgba(25, 118, 210, 0.1)',
    transform: 'translateY(-2px)',
  },
}));

const HandicapRow = styled(Box)(({ theme }) => ({
  display: 'flex',
  alignItems: 'center',
  justifyContent: 'space-between',
  gap: theme.spacing(3),
  [theme.breakpoints.down('sm')]: {
    flexDirection: 'column',
    alignItems: 'stretch',
  },
}));

const HandicapAnalysis = styled(Box)(({ theme }) => ({
  marginTop: theme.spacing(2),
  padding: theme.spacing(2),
  backgroundColor: 'rgba(25, 118, 210, 0.08)',
  borderRadius: theme.spacing(1),
  '& .MuiTypography-root': {
    color: theme.palette.text.secondary,
  }
}));

const HandicapSelect = styled(FormControl)(({ theme }) => ({
  minWidth: 150,
  '& .MuiOutlinedInput-root': {
    borderRadius: theme.spacing(1),
    backgroundColor: 'rgba(255, 255, 255, 0.05)',
    transition: 'all 0.3s ease-in-out',
    '&:hover': {
      backgroundColor: 'rgba(255, 255, 255, 0.1)',
      transform: 'translateY(-2px)',
    },
    '&.Mui-focused': {
      backgroundColor: 'rgba(255, 255, 255, 0.15)',
      transform: 'translateY(-2px)',
      boxShadow: '0 4px 20px rgba(25, 118, 210, 0.25)',
    }
  },
  '& .MuiSelect-select': {
    padding: theme.spacing(1.5),
    textAlign: 'center',
    fontSize: '1.1rem',
    fontWeight: 500,
  },
  '& .MuiInputLabel-root': {
    fontSize: '0.9rem',
    fontWeight: 500,
    '&.Mui-focused': {
      color: theme.palette.primary.main,
    }
  },
}));

// 添加全局factorial函数
const factorial = (n: number): number => {
  if (n === 0 || n === 1) return 1;
  return n * factorial(n - 1);
};

const App: React.FC = () => {
  const theme = useTheme();

  const [homeTeam, setHomeTeam] = useState<TeamData>({
    h2h: { wins: 0, draws: 0, losses: 0, goalsFor: 0, goalsAgainst: 0 },
    recent: { wins: 0, draws: 0, losses: 0, goalsFor: 0, goalsAgainst: 0 },
  });

  const [awayTeam, setAwayTeam] = useState<TeamData>({
    h2h: { wins: 0, draws: 0, losses: 0, goalsFor: 0, goalsAgainst: 0 },
    recent: { wins: 0, draws: 0, losses: 0, goalsFor: 0, goalsAgainst: 0 },
  });

  const [prediction, setPrediction] = useState<{
    result: string;
    confidence: number;
    models: { name: string; prediction: string; confidence: number; detailedConfidence: any; weight: number }[];
  } | null>(null);

  const [isCalculating, setIsCalculating] = useState(false);
  const [showResults, setShowResults] = useState(false);

  // Add new state for Asian handicap
  const [asianHandicap, setAsianHandicap] = useState({
    value: 0,
    odds: {
      home: 0.95,
      away: 0.95
    }
  });

  // Add new state for Asian handicap analysis
  const [handicapAnalysis, setHandicapAnalysis] = useState({
    recommendation: '',
    confidence: 0,
    explanation: ''
  });

  // Add handicap options
  const handicapOptions = [
    { value: 2.5, label: '让2球半' },
    { value: 2.25, label: '让2球/2球半' },
    { value: 2, label: '让2球' },
    { value: 1.75, label: '让1球半/2球' },
    { value: 1.5, label: '让1球半' },
    { value: 1.25, label: '让1球/1球半' },
    { value: 1, label: '让1球' },
    { value: 0.75, label: '让半球/1球' },
    { value: 0.5, label: '让半球' },
    { value: 0.25, label: '让平/半' },
    { value: 0, label: '平手' },
    { value: -0.25, label: '受平/半' },
    { value: -0.5, label: '受半球' },
    { value: -0.75, label: '受半球/1球' },
    { value: -1, label: '受1球' },
    { value: -1.25, label: '受1球/1球半' },
    { value: -1.5, label: '受1球半' },
    { value: -1.75, label: '受1球半/2球' },
    { value: -2, label: '受2球' },
    { value: -2.25, label: '受2球/2球半' },
    { value: -2.5, label: '受2球半' }
  ];

  // 移动renderModelDetails到组件顶部
  const renderModelDetails = (model: {
    name: string;
    prediction: string;
    confidence: number;
    detailedConfidence: {
      homeWin: number;
      draw: number;
      awayWin: number;
    };
    weight: number;
    explanation?: string;
  }) => (
    <Box 
      sx={{ 
        bgcolor: 'rgba(255,255,255,0.1)', 
        p: 2, 
        borderRadius: 2,
        transition: 'transform 0.3s ease-in-out',
        '&:hover': {
          transform: 'scale(1.05)',
          bgcolor: 'rgba(255,255,255,0.15)',
        }
      }}
    >
      <Typography variant="subtitle1">{model.name}</Typography>
      <Typography variant="body2">预测：{model.prediction}</Typography>
      <Typography variant="body2">
        主胜：{model.detailedConfidence.homeWin.toFixed(1)}%
      </Typography>
      <Typography variant="body2">
        平局：{model.detailedConfidence.draw.toFixed(1)}%
      </Typography>
      <Typography variant="body2">
        客胜：{model.detailedConfidence.awayWin.toFixed(1)}%
      </Typography>
      <Typography variant="body2">
        权重：{(model.weight * 100).toFixed(0)}%
      </Typography>
      {model.explanation && (
        <Typography variant="body2" sx={{ mt: 1, color: 'rgba(255,255,255,0.7)' }}>
          分析：{model.explanation}
        </Typography>
      )}
      <LinearProgress
        variant="determinate"
        value={model.confidence}
        sx={{
          mt: 1,
          height: 4,
          borderRadius: 2,
          backgroundColor: 'rgba(255,255,255,0.1)',
          '& .MuiLinearProgress-bar': {
            backgroundColor: 'white',
          }
        }}
      />
    </Box>
  );

  const calculatePrediction = () => {
    setIsCalculating(true);
    setShowResults(false);
    
    setTimeout(() => {
      // 计算基础数据
      const homeForm = calculateFormStrength(homeTeam.recent);
      const awayForm = calculateFormStrength(awayTeam.recent);
      const h2hAdvantage = calculateHeadToHeadAdvantage(homeTeam.h2h);
      const matchContext = calculateMatchImportance(homeTeam, awayTeam);

      // 计算高级指标
      const homeAdvancedMetrics = calculateAdvancedMetrics(homeTeam.recent);
      const awayAdvancedMetrics = calculateAdvancedMetrics(awayTeam.recent);
      const matchupDynamics = calculateMatchupDynamics(homeTeam, awayTeam, homeAdvancedMetrics, awayAdvancedMetrics);
      const homeTrends = calculateSeasonalTrends(homeTeam.recent);
      const awayTrends = calculateSeasonalTrends(awayTeam.recent);
      const pressureIndices = calculatePressureIndex(homeTeam, awayTeam, matchContext);

      // 计算主场优势加成
      const homeAdvantageBonus = calculateHomeAdvantageBonus(homeTeam, awayTeam, matchContext);

      // 计算基础胜率
      const baseHomeWinProb = (
        homeForm.overallScore * 0.3 +
        h2hAdvantage.overallAdvantage * 0.2 +
        matchupDynamics.homeStrength * 0.2 +
        (100 - pressureIndices.homePressure) * 0.15 +
        homeAdvancedMetrics.attack.attackingThreat * 0.15
      );

      const baseAwayWinProb = (
        awayForm.overallScore * 0.3 +
        (100 - h2hAdvantage.overallAdvantage) * 0.2 +
        matchupDynamics.awayStrength * 0.2 +
        (100 - pressureIndices.awayPressure) * 0.15 +
        awayAdvancedMetrics.attack.attackingThreat * 0.15
      );

      // 应用主场优势
      const homeWinProb = baseHomeWinProb * (1 + homeAdvantageBonus);
      const awayWinProb = baseAwayWinProb;
      const drawProb = calculateDrawProbability(homeWinProb, awayWinProb, homeTeam, awayTeam, matchContext);

      // 添加新模型的预测结果
      const poissonResult = calculatePoissonModel(homeTeam, awayTeam, homeAdvancedMetrics, awayAdvancedMetrics);
      const eloResult = calculateEloModel(homeTeam, awayTeam);
      const dixonColesResult = calculateDixonColesModel(homeTeam, awayTeam, homeAdvancedMetrics, awayAdvancedMetrics);

      // 计算归一化概率
      const totalProb = homeWinProb + awayWinProb + drawProb;
      const normalizedHomeWinProb = (homeWinProb / totalProb) * 100;
      const normalizedAwayWinProb = (awayWinProb / totalProb) * 100;
      const normalizedDrawProb = (drawProb / totalProb) * 100;

      // 综合所有模型的预测结果
      const combinedHomeWinProb = (
        normalizedHomeWinProb * 0.3 +
        poissonResult.homeWin * 0.2 +
        eloResult.homeWin * 0.2 +
        dixonColesResult.homeWin * 0.3
      );

      const combinedAwayWinProb = (
        normalizedAwayWinProb * 0.3 +
        poissonResult.awayWin * 0.2 +
        eloResult.awayWin * 0.2 +
        dixonColesResult.awayWin * 0.3
      );

      const combinedDrawProb = (
        normalizedDrawProb * 0.3 +
        poissonResult.draw * 0.2 +
        eloResult.draw * 0.2 +
        dixonColesResult.draw * 0.3
      );

      // Calculate handicap analysis
      const handicapResult = analyzeHandicap();

      // Update models list to include handicap analysis
      const models = [
        {
          name: '亚盘分析',
          prediction: handicapResult.prediction === '主队受让' || handicapResult.prediction === '主队' ? '主胜' :
                     handicapResult.prediction === '客队加' || handicapResult.prediction === '客队让' || handicapResult.prediction === '客队' ? '客胜' :
                     handicapResult.prediction === '观望' ? '平局' : handicapResult.prediction,
          confidence: handicapResult.confidence,
          detailedConfidence: {
            homeWin: handicapResult.prediction === '主队受让' || handicapResult.prediction === '主队' ? handicapResult.confidence : 
                    handicapResult.prediction === '观望' ? 33.33 : 100 - handicapResult.confidence,
            draw: handicapResult.prediction === '观望' ? handicapResult.confidence : 
                  Math.min(100 - Math.abs(handicapResult.confidence - 50), 20),
            awayWin: handicapResult.prediction === '客队加' || handicapResult.prediction === '客队让' || handicapResult.prediction === '客队' ? handicapResult.confidence :
                    handicapResult.prediction === '观望' ? 33.33 : 100 - handicapResult.confidence
          },
          weight: 0.3,
          explanation: handicapResult.explanation
        },
        {
          name: '整体实力',
          prediction: homeForm.overallScore > awayForm.overallScore ? '主胜' : '客胜',
          confidence: Math.abs(homeForm.overallScore - awayForm.overallScore),
          detailedConfidence: {
            homeWin: normalizedHomeWinProb,
            draw: normalizedDrawProb,
            awayWin: normalizedAwayWinProb
          },
          weight: 0.2
        },
        {
          name: '历史交锋',
          prediction: h2hAdvantage.overallAdvantage > 50 ? '主胜' : '客胜',
          confidence: Math.abs(h2hAdvantage.overallAdvantage - 50) * 2,
          detailedConfidence: {
            homeWin: h2hAdvantage.overallAdvantage,
            draw: Math.min(100 - Math.abs(h2hAdvantage.overallAdvantage - 50) * 2, 30),
            awayWin: 100 - h2hAdvantage.overallAdvantage
          },
          weight: 0.2
        },
        {
          name: '泊松模型',
          prediction: poissonResult.prediction,
          confidence: poissonResult.confidence,
          detailedConfidence: {
            homeWin: poissonResult.homeWin,
            draw: poissonResult.draw,
            awayWin: poissonResult.awayWin
          },
          weight: 0.15
        },
        {
          name: 'ELO评级',
          prediction: eloResult.homeWin > eloResult.awayWin ? '主胜' : '客胜',
          confidence: Math.abs(eloResult.homeWin - eloResult.awayWin),
          detailedConfidence: {
            homeWin: eloResult.homeWin,
            draw: eloResult.draw,
            awayWin: eloResult.awayWin
          },
          weight: 0.15
        }
      ];

      // Calculate final prediction considering all models including handicap
      let weightedHomeWin = 0;
      let weightedDraw = 0;
      let weightedAwayWin = 0;

      models.forEach(model => {
        weightedHomeWin += model.detailedConfidence.homeWin * model.weight;
        weightedDraw += model.detailedConfidence.draw * model.weight;
        weightedAwayWin += model.detailedConfidence.awayWin * model.weight;
      });

      const finalHomeWinProb = weightedHomeWin;
      const finalDrawProb = weightedDraw;
      const finalAwayWinProb = weightedAwayWin;

      let finalPrediction = '';
      let confidence = 0;

      if (finalHomeWinProb > finalAwayWinProb + 15 && finalHomeWinProb > finalDrawProb + 18) {
        finalPrediction = '主胜';
        confidence = finalHomeWinProb;
      } else if (finalAwayWinProb > finalHomeWinProb + 12 && finalAwayWinProb > finalDrawProb + 15) {
        finalPrediction = '客胜';
        confidence = finalAwayWinProb;
      } else {
        finalPrediction = '平局';
        confidence = finalDrawProb;
      }

      setPrediction({
        result: finalPrediction,
        confidence: Math.min(confidence, 100),
        models
      });

      setIsCalculating(false);
      setShowResults(true);
    }, 1500);
  };

  // 计算球队势头
  const calculateMomentum = (data: MatchData) => {
    const totalMatches = data.wins + data.draws + data.losses;
    const winRate = data.wins / totalMatches;
    const goalDiff = (data.goalsFor - data.goalsAgainst) / totalMatches;
    return (winRate * 0.7 + goalDiff * 0.3);
  };

  // 添加新的计算函数
  const calculateFormStrength = (data: MatchData) => {
    // 计算近期状态强度
    const totalMatches = data.wins + data.draws + data.losses;
    const winPoints = data.wins * 3;
    const drawPoints = data.draws;
    const totalPossiblePoints = totalMatches * 3;
    const pointsPercentage = ((winPoints + drawPoints) / totalPossiblePoints) * 100;
    
    // 计算进攻效率
    const scoringEfficiency = (data.goalsFor / totalMatches) * 100;
    
    // 计算防守效率
    const defensiveEfficiency = (1 - (data.goalsAgainst / (totalMatches * 3))) * 100;
    
    return {
      formScore: pointsPercentage,
      attackScore: scoringEfficiency,
      defenseScore: defensiveEfficiency,
      overallScore: (pointsPercentage * 0.4 + scoringEfficiency * 0.3 + defensiveEfficiency * 0.3)
    };
  };

  const calculateHeadToHeadAdvantage = (h2hData: MatchData) => {
    const totalMatches = h2hData.wins + h2hData.draws + h2hData.losses;
    const winPercentage = (h2hData.wins / totalMatches) * 100;
    const goalDifference = h2hData.goalsFor - h2hData.goalsAgainst;
    const goalDiffPerMatch = goalDifference / totalMatches;
    
    return {
      dominanceScore: winPercentage,
      goalSuperiority: goalDiffPerMatch * 20, // 将每场比赛的进球差转换为0-100的分数
      overallAdvantage: (winPercentage * 0.6 + (goalDiffPerMatch * 20) * 0.4)
    };
  };

  const calculateMatchImportance = (homeTeam: TeamData, awayTeam: TeamData) => {
    // 基于近期表现计算比赛重要性
    const homeForm = calculateFormStrength(homeTeam.recent);
    const awayForm = calculateFormStrength(awayTeam.recent);
    
    // 计算势头差异
    const formDifference = Math.abs(homeForm.overallScore - awayForm.overallScore);
    
    // 根据势头差异调整重要性
    const importance = formDifference < 10 ? 'high' : formDifference < 20 ? 'medium' : 'low';
    
    return {
      importance,
      homeFormScore: homeForm.overallScore,
      awayFormScore: awayForm.overallScore,
      scoreDifference: formDifference
    };
  };

  const calculatePsychologicalFactor = (homeTeam: TeamData, awayTeam: TeamData) => {
    // 计算主队心理优势
    const homeWinStreak = homeTeam.recent.wins / (homeTeam.recent.wins + homeTeam.recent.draws + homeTeam.recent.losses);
    const homeGoalDiff = homeTeam.recent.goalsFor - homeTeam.recent.goalsAgainst;
    
    // 计算客队心理压力
    const awayWinStreak = awayTeam.recent.wins / (awayTeam.recent.wins + awayTeam.recent.draws + awayTeam.recent.losses);
    const awayGoalDiff = awayTeam.recent.goalsFor - awayTeam.recent.goalsAgainst;
    
    // 计算心理因素得分
    const homePsychScore = (homeWinStreak * 60 + (homeGoalDiff > 0 ? 40 : 20));
    const awayPsychScore = (awayWinStreak * 50 + (awayGoalDiff > 0 ? 30 : 15));
    
    return {
      homePsychological: homePsychScore,
      awayPsychological: awayPsychScore,
      psychAdvantage: homePsychScore - awayPsychScore
    };
  };

  // 添加新的高级分析模型
  const calculateAdvancedMetrics = (data: MatchData) => {
    const totalMatches = data.wins + data.draws + data.losses;
    
    // 进攻指标
    const goalsPerGame = data.goalsFor / totalMatches;
    const scoringEfficiency = data.goalsFor / (data.wins + data.draws);
    const attackingThreat = (goalsPerGame * 0.6 + scoringEfficiency * 0.4) * 100;
    
    // 防守指标
    const goalsAgainstPerGame = data.goalsAgainst / totalMatches;
    const cleanSheetRatio = (totalMatches - (data.goalsAgainst > 0 ? totalMatches : 0)) / totalMatches;
    const defensiveSolidity = (1 - (goalsAgainstPerGame / 3)) * 100;
    
    // 稳定性指标
    const consistencyScore = (
      (data.wins / totalMatches) * 100 * 0.5 +
      (1 - Math.abs(data.wins - data.losses) / totalMatches) * 100 * 0.3 +
      (data.draws / totalMatches) * 100 * 0.2
    );

    // 势头指标
    const momentumScore = (
      (data.wins * 3 + data.draws) / (totalMatches * 3) * 100 * 0.7 +
      (data.goalsFor - data.goalsAgainst) / (totalMatches * 2) * 100 * 0.3
    );

    return {
      attack: {
        goalsPerGame,
        scoringEfficiency,
        attackingThreat
      },
      defense: {
        goalsAgainstPerGame,
        cleanSheetRatio,
        defensiveSolidity
      },
      stability: {
        consistencyScore,
        momentumScore
      }
    };
  };

  const calculateMatchupDynamics = (
    homeTeam: TeamData,
    awayTeam: TeamData,
    homeMetrics: ReturnType<typeof calculateAdvancedMetrics>,
    awayMetrics: ReturnType<typeof calculateAdvancedMetrics>
  ) => {
    // 计算比赛动态优势
    const homeAttackVsAwayDefense = (
      homeMetrics.attack.attackingThreat * 0.6 +
      (100 - awayMetrics.defense.defensiveSolidity) * 0.4
    );

    const awayAttackVsHomeDefense = (
      awayMetrics.attack.attackingThreat * 0.5 +
      (100 - homeMetrics.defense.defensiveSolidity) * 0.5
    );

    // 计算整体优势
    const homeAdvantage = (
      homeMetrics.stability.consistencyScore * 0.3 +
      homeMetrics.stability.momentumScore * 0.3 +
      homeAttackVsAwayDefense * 0.4
    );

    const awayAdvantage = (
      awayMetrics.stability.consistencyScore * 0.25 +
      awayMetrics.stability.momentumScore * 0.25 +
      awayAttackVsHomeDefense * 0.5
    );

    return {
      homeStrength: homeAdvantage,
      awayStrength: awayAdvantage,
      dynamicDifference: homeAdvantage - awayAdvantage
    };
  };

  const calculateSeasonalTrends = (data: MatchData) => {
    const totalMatches = data.wins + data.draws + data.losses;
    
    // 进攻趋势
    const attackingTrend = (
      (data.goalsFor / totalMatches) * 2 + // 场均进球
      (data.wins / totalMatches) + // 胜率
      (data.goalsFor / (data.wins + data.draws)) // 得分效率
    ) / 4 * 100;

    // 防守趋势
    const defendingTrend = (
      (1 - data.goalsAgainst / (totalMatches * 3)) + // 防守效率
      (1 - data.losses / totalMatches) + // 不败率
      (data.draws / totalMatches) * 0.5 // 控制能力
    ) / 2.5 * 100;

    // 整体趋势
    const overallTrend = (
      attackingTrend * 0.4 +
      defendingTrend * 0.4 +
      (data.wins * 3 + data.draws) / (totalMatches * 3) * 100 * 0.2
    );

    return {
      attackingTrend,
      defendingTrend,
      overallTrend
    };
  };

  const calculatePressureIndex = (
    homeTeam: TeamData,
    awayTeam: TeamData,
    matchContext: ReturnType<typeof calculateMatchImportance>
  ) => {
    // 计算主队压力指数
    const homePressure = (
      (homeTeam.recent.losses / 10) * 30 + // 近期失利压力
      (homeTeam.h2h.losses / 6) * 20 + // 交锋失利压力
      (matchContext.importance === 'high' ? 30 : matchContext.importance === 'medium' ? 20 : 10) + // 比赛重要性压力
      (homeTeam.recent.goalsAgainst > homeTeam.recent.goalsFor ? 20 : 0) // 进失球压力
    );

    // 计算客队压力指数
    const awayPressure = (
      (awayTeam.recent.losses / 10) * 35 + // 近期失利压力（客场更重）
      (awayTeam.h2h.losses / 6) * 25 + // 交锋失利压力
      (matchContext.importance === 'high' ? 25 : matchContext.importance === 'medium' ? 15 : 5) + // 比赛重要性压力
      (awayTeam.recent.goalsAgainst > awayTeam.recent.goalsFor ? 15 : 0) // 进失球压力
    );

    return {
      homePressure,
      awayPressure,
      pressureDifferential: homePressure - awayPressure
    };
  };

  // 优化EOL模型计算
  const calculateEOL = (
    homeTeam: TeamData,
    awayTeam: TeamData,
    homeForm: ReturnType<typeof calculateFormStrength>,
    awayForm: ReturnType<typeof calculateFormStrength>,
    homeMetrics: ReturnType<typeof calculateAdvancedMetrics>,
    awayMetrics: ReturnType<typeof calculateAdvancedMetrics>
  ) => {
    const homeExpectedGoals = (
      (homeTeam.recent.goalsFor / 6) * 1.1 * // 修改为6场
      (homeForm.attackScore / 100) *
      (homeMetrics.attack.scoringEfficiency / 2) *
      (1 + (1 - awayMetrics.defense.defensiveSolidity / 100))
    );

    const awayExpectedGoals = (
      (awayTeam.recent.goalsFor / 6) * 0.9 * // 修改为6场
      (awayForm.attackScore / 100) *
      (awayMetrics.attack.scoringEfficiency / 2) *
      (1 + (1 - homeMetrics.defense.defensiveSolidity / 100))
    );

    const goalDiff = homeExpectedGoals - awayExpectedGoals;
    const winProb = goalDiff > 0 ? 
      Math.min((goalDiff / homeExpectedGoals) * 100, 100) : 
      Math.max((goalDiff / awayExpectedGoals) * 100, -100);

    return {
      prediction: winProb > 20 ? '主胜' : winProb < -15 ? '客胜' : '平局',
      confidence: Math.abs(winProb)
    };
  };

  // 优化攻防指数模型
  const calculateAttackDefenseIndex = (
    homeTeam: TeamData,
    awayTeam: TeamData,
    homeForm: ReturnType<typeof calculateFormStrength>,
    awayForm: ReturnType<typeof calculateFormStrength>,
    h2hAdvantage: ReturnType<typeof calculateHeadToHeadAdvantage>,
    matchupDynamics: ReturnType<typeof calculateMatchupDynamics>
  ) => {
    const homeAttackStrength = (
      homeForm.attackScore * 0.3 +
      (homeTeam.recent.goalsFor / 10) * 25 +
      h2hAdvantage.goalSuperiority * 0.25 +
      matchupDynamics.homeStrength * 0.2
    );

    const awayAttackStrength = (
      awayForm.attackScore * 0.3 +
      (awayTeam.recent.goalsFor / 10) * 20 +
      (100 - h2hAdvantage.goalSuperiority) * 0.25 +
      matchupDynamics.awayStrength * 0.25
    );

    const homeDefenseStrength = (
      homeForm.defenseScore * 0.3 +
      (1 - homeTeam.recent.goalsAgainst / (10 * 3)) * 25 +
      h2hAdvantage.dominanceScore * 0.25 +
      matchupDynamics.homeStrength * 0.2
    );

    const awayDefenseStrength = (
      awayForm.defenseScore * 0.3 +
      (1 - awayTeam.recent.goalsAgainst / (10 * 3)) * 20 +
      (100 - h2hAdvantage.dominanceScore) * 0.25 +
      matchupDynamics.awayStrength * 0.25
    );

    const strengthDiff = (
      (homeAttackStrength - awayDefenseStrength) -
      (awayAttackStrength - homeDefenseStrength)
    );

    return {
      prediction: strengthDiff > 10 ? '主胜' : strengthDiff < -8 ? '客胜' : '平局',
      confidence: Math.abs(strengthDiff)
    };
  };

  // 新增：计算主场优势加成
  const calculateHomeAdvantageBonus = (
    homeTeam: TeamData,
    awayTeam: TeamData,
    matchContext: ReturnType<typeof calculateMatchImportance>
  ) => {
    const homeStrength = homeTeam.recent.wins * 3 + homeTeam.recent.draws;
    const awayStrength = awayTeam.recent.wins * 3 + awayTeam.recent.draws;
    const strengthDiff = Math.abs(homeStrength - awayStrength);

    // 基础主场优势
    let bonus = 0.1;

    // 根据实力差距调整
    if (homeStrength > awayStrength) {
      bonus += 0.05; // 主队更强时增加优势
    } else if (strengthDiff > 9) {
      bonus -= 0.03; // 实力差距过大时降低优势
    }

    // 根据比赛重要性调整
    if (matchContext.importance === 'high') {
      bonus += 0.05;
    }

    // 根据近期状态调整
    const homeRecentForm = homeTeam.recent.wins / (homeTeam.recent.wins + homeTeam.recent.draws + homeTeam.recent.losses);
    if (homeRecentForm > 0.6) {
      bonus += 0.03;
    }

    return Math.min(bonus, 0.25); // 限制最大主场优势
  };

  // 新增：优化平局概率计算
  const calculateDrawProbability = (
    homeWinProb: number,
    awayWinProb: number,
    homeTeam: TeamData,
    awayTeam: TeamData,
    matchContext: ReturnType<typeof calculateMatchImportance>
  ) => {
    // 基础平局概率
    let drawProb = Math.max(0, 100 - homeWinProb - awayWinProb);

    // 根据实力差距调整
    const strengthDiff = Math.abs(
      (homeTeam.recent.wins * 3 + homeTeam.recent.draws) -
      (awayTeam.recent.wins * 3 + awayTeam.recent.draws)
    );

    if (strengthDiff < 6) {
      drawProb *= 1.2; // 实力接近时增加平局概率
    }

    // 根据进球数调整
    const homeGoalsPerGame = homeTeam.recent.goalsFor / (homeTeam.recent.wins + homeTeam.recent.draws + homeTeam.recent.losses);
    const awayGoalsPerGame = awayTeam.recent.goalsFor / (awayTeam.recent.wins + awayTeam.recent.draws + awayTeam.recent.losses);

    if (homeGoalsPerGame < 1.5 && awayGoalsPerGame < 1.5) {
      drawProb *= 1.15; // 两队都不善进球时增加平局概率
    }

    // 根据比赛重要性调整
    if (matchContext.importance === 'high') {
      drawProb *= 0.9; // 重要比赛降低平局概率
    }

    return Math.min(drawProb, 40); // 限制最大平局概率
  };

  // 添加新的预测模型
  const calculatePoissonModel = (
    homeTeam: TeamData,
    awayTeam: TeamData,
    homeMetrics: ReturnType<typeof calculateAdvancedMetrics>,
    awayMetrics: ReturnType<typeof calculateAdvancedMetrics>
  ) => {
    // 1. 安全的除法函数
    const safeDivide = (numerator: number, denominator: number, defaultValue: number = 0): number => {
      if (denominator === 0 || isNaN(denominator) || isNaN(numerator)) {
        return defaultValue;
      }
      return numerator / denominator;
    };

    // 2. 计算进攻效率指标
    const calculateAttackingIndex = (team: TeamData, metrics: ReturnType<typeof calculateAdvancedMetrics>) => {
      const totalMatches = Math.max(team.recent.wins + team.recent.draws + team.recent.losses, 1);
      const totalH2HMatches = Math.max(team.h2h.wins + team.h2h.draws + team.h2h.losses, 1);
      
      const recentGoalsPerGame = safeDivide(team.recent.goalsFor, totalMatches, 1);
      const h2hGoalsPerGame = safeDivide(team.h2h.goalsFor, totalH2HMatches, 1);
      const attackingEfficiency = Math.max(0, Math.min(metrics.attack.scoringEfficiency, 100)) / 100;
      
      return Math.max(0.1, 
        recentGoalsPerGame * 0.5 +
        h2hGoalsPerGame * 0.3 +
        attackingEfficiency * 0.2
      );
    };

    // 3. 计算防守效率指标
    const calculateDefensiveIndex = (team: TeamData, metrics: ReturnType<typeof calculateAdvancedMetrics>) => {
      const totalMatches = Math.max(team.recent.wins + team.recent.draws + team.recent.losses, 1);
      const totalH2HMatches = Math.max(team.h2h.wins + team.h2h.draws + team.h2h.losses, 1);
      
      const recentGoalsConcededPerGame = safeDivide(team.recent.goalsAgainst, totalMatches, 1);
      const h2hGoalsConcededPerGame = safeDivide(team.h2h.goalsAgainst, totalH2HMatches, 1);
      const defensiveSolidity = Math.max(0, Math.min(metrics.defense.defensiveSolidity, 100)) / 100;
      
      return Math.max(0.1,
        (1 - recentGoalsConcededPerGame / 3) * 0.5 +
        (1 - h2hGoalsConcededPerGame / 3) * 0.3 +
        defensiveSolidity * 0.2
      );
    };

    // 4. 计算球队状态指标
    const calculateFormIndex = (team: TeamData) => {
      const totalMatches = Math.max(team.recent.wins + team.recent.draws + team.recent.losses, 1);
      const totalH2HMatches = Math.max(team.h2h.wins + team.h2h.draws + team.h2h.losses, 1);
      
      const recentWinRate = safeDivide(team.recent.wins, totalMatches, 0.33);
      const h2hWinRate = safeDivide(team.h2h.wins, totalH2HMatches, 0.33);
      
      return Math.max(0.1, recentWinRate * 0.7 + h2hWinRate * 0.3);
    };

    // 5. 计算预期进球数
    const homeAttackIndex = calculateAttackingIndex(homeTeam, homeMetrics);
    const awayAttackIndex = calculateAttackingIndex(awayTeam, awayMetrics);
    const homeDefenseIndex = calculateDefensiveIndex(homeTeam, homeMetrics);
    const awayDefenseIndex = calculateDefensiveIndex(awayTeam, awayMetrics);
    const homeFormIndex = calculateFormIndex(homeTeam);
    const awayFormIndex = calculateFormIndex(awayTeam);

    // 6. 计算基础预期进球
    const homeBaseExpectedGoals = Math.max(0.1, homeAttackIndex * (1 - awayDefenseIndex) * 2.0);
    const awayBaseExpectedGoals = Math.max(0.1, awayAttackIndex * (1 - homeDefenseIndex) * 2.0);

    // 7. 应用状态调整
    const homeExpectedGoals = Math.max(0.1, homeBaseExpectedGoals * 
      (1 + homeFormIndex * 0.2) * // 状态调整
      1.25); // 主场加成

    const awayExpectedGoals = Math.max(0.1, awayBaseExpectedGoals *
      (1 + awayFormIndex * 0.2)); // 状态调整

    // 8. 计算泊松分布概率
    const calculatePoissonProbability = (lambda: number, k: number): number => {
      if (k < 0 || !isFinite(lambda) || isNaN(lambda)) return 0;
      if (lambda <= 0) return k === 0 ? 1 : 0;
      
      try {
        let result = Math.exp(-lambda);
        for (let i = 1; i <= k; i++) {
          result *= (lambda / i);
        }
        return isFinite(result) ? result : 0;
      } catch (e) {
        return 0;
      }
    };

    // 9. 计算各个比分的概率
    const maxGoals = 6;
    let probMatrix: number[][] = Array(maxGoals + 1).fill(0).map(() => Array(maxGoals + 1).fill(0));
    let homeWinProb = 0;
    let drawProb = 0;
    let awayWinProb = 0;

    // 10. 填充概率矩阵
    for (let i = 0; i <= maxGoals; i++) {
      for (let j = 0; j <= maxGoals; j++) {
        const homeProb = calculatePoissonProbability(homeExpectedGoals, i);
        const awayProb = calculatePoissonProbability(awayExpectedGoals, j);
        
        if (!isFinite(homeProb) || !isFinite(awayProb)) continue;
        
        const correlationFactor = i === j ? 1.1 : 
                                 Math.abs(i - j) === 1 ? 0.9 : 1.0;

        probMatrix[i][j] = homeProb * awayProb * correlationFactor;
        
        if (i > j) {
          homeWinProb += probMatrix[i][j];
        } else if (i === j) {
          drawProb += probMatrix[i][j];
        } else {
          awayWinProb += probMatrix[i][j];
        }
      }
    }

    // 11. 概率归一化
    const totalProb = Math.max(0.000001, homeWinProb + drawProb + awayWinProb);
    homeWinProb = (homeWinProb / totalProb) * 100;
    drawProb = (drawProb / totalProb) * 100;
    awayWinProb = (awayWinProb / totalProb) * 100;

    // 12. 确保概率有效
    if (isNaN(homeWinProb) || !isFinite(homeWinProb)) homeWinProb = 33.33;
    if (isNaN(drawProb) || !isFinite(drawProb)) drawProb = 33.34;
    if (isNaN(awayWinProb) || !isFinite(awayWinProb)) awayWinProb = 33.33;

    // 13. 平局概率限制
    const maxDrawProbability = 28;
    if (drawProb > maxDrawProbability) {
      const excessDrawProb = drawProb - maxDrawProbability;
      drawProb = maxDrawProbability;
      
      const winRatio = safeDivide(homeWinProb, (homeWinProb + awayWinProb), 0.5);
      homeWinProb += excessDrawProb * winRatio;
      awayWinProb += excessDrawProb * (1 - winRatio);
    }

    // 14. 计算预测结果
    const winThreshold = 8;
    let prediction = '';
    let confidence = 0;

    if (homeWinProb > awayWinProb + winThreshold && homeWinProb > drawProb + winThreshold) {
      prediction = '主胜';
      confidence = homeWinProb;
    } else if (awayWinProb > homeWinProb + winThreshold && awayWinProb > drawProb + winThreshold) {
      prediction = '客胜';
      confidence = awayWinProb;
    } else {
      prediction = '平局';
      confidence = drawProb;
    }

    // 15. 返回结果
    return {
      homeWin: Math.round(homeWinProb * 10) / 10,
      draw: Math.round(drawProb * 10) / 10,
      awayWin: Math.round(awayWinProb * 10) / 10,
      prediction,
      confidence: Math.round(confidence * 10) / 10,
      expectedGoals: {
        home: Math.round(homeExpectedGoals * 100) / 100,
        away: Math.round(awayExpectedGoals * 100) / 100
      }
    };
  };

  // 优化ELO模型
  const calculateEloModel = (homeTeam: TeamData, awayTeam: TeamData) => {
    // 计算基础ELO分
    const calculateBaseElo = (team: TeamData) => {
      const recentPerformance = team.recent.wins * 3 + team.recent.draws;
      const h2hPerformance = team.h2h.wins * 3 + team.h2h.draws;
      const goalDiff = team.recent.goalsFor - team.recent.goalsAgainst;
      
      return 1500 + // 基础分
        (recentPerformance * 25) + // 近期表现
        (h2hPerformance * 15) + // 交锋记录
        (goalDiff * 10); // 进球差
    };

    const homeElo = calculateBaseElo(homeTeam);
    const awayElo = calculateBaseElo(awayTeam);
    const eloDiff = (homeElo - awayElo) * 1.1; // 考虑主场优势

    // 计算胜率
    const homeWinProb = 1 / (1 + Math.pow(10, -eloDiff / 400));
    const drawProb = 0.25 - Math.abs(homeWinProb - 0.5) * 0.2; // 调整平局概率计算
    const awayWinProb = 1 - homeWinProb - drawProb;

    return {
      homeWin: homeWinProb * 100,
      draw: drawProb * 100,
      awayWin: awayWinProb * 100
    };
  };

  // 优化Dixon-Coles模型
  const calculateDixonColesModel = (
    homeTeam: TeamData,
    awayTeam: TeamData,
    homeMetrics: ReturnType<typeof calculateAdvancedMetrics>,
    awayMetrics: ReturnType<typeof calculateAdvancedMetrics>
  ) => {
    // 计算进攻强度
    const homeAttackStrength = (
      homeMetrics.attack.attackingThreat / 100 *
      (homeTeam.recent.goalsFor / 6) * // 修改为6场
      Math.pow(homeTeam.h2h.goalsFor / 6, 0.3)
    );
    
    const awayAttackStrength = (
      awayMetrics.attack.attackingThreat / 100 *
      (awayTeam.recent.goalsFor / 6) * // 修改为6场
      Math.pow(awayTeam.h2h.goalsFor / 6, 0.3)
    );
    
    // 计算防守强度
    const homeDefenseStrength = (
      homeMetrics.defense.defensiveSolidity / 100 *
      (1 - homeTeam.recent.goalsAgainst / (6 * 3)) * // 修改为6场
      Math.pow(1 - homeTeam.h2h.goalsAgainst / (6 * 3), 0.3)
    );
    
    const awayDefenseStrength = (
      awayMetrics.defense.defensiveSolidity / 100 *
      (1 - awayTeam.recent.goalsAgainst / (6 * 3)) * // 修改为6场
      Math.pow(1 - awayTeam.h2h.goalsAgainst / (6 * 3), 0.3)
    );

    // 计算预期进球
    const homeExpectedGoals = homeAttackStrength * (1 - awayDefenseStrength) * 1.15; // 增加主场加成
    const awayExpectedGoals = awayAttackStrength * (1 - homeDefenseStrength);

    // 计算相关系数
    const rho = calculateGoalCorrelation(homeTeam, awayTeam);

    // 计算修正后的概率
    const probMatrix = calculateProbabilityMatrix(homeExpectedGoals, awayExpectedGoals, rho);

    return {
      homeWin: probMatrix.homeWin,
      draw: probMatrix.draw,
      awayWin: probMatrix.awayWin
    };
  };

  // 计算进球相关性
  const calculateGoalCorrelation = (homeTeam: TeamData, awayTeam: TeamData) => {
    const homeGoalsPerGame = homeTeam.recent.goalsFor / 10;
    const awayGoalsPerGame = awayTeam.recent.goalsFor / 10;
    const avgGoals = (homeGoalsPerGame + awayGoalsPerGame) / 2;

    // 根据场均进球调整相关系数
    return avgGoals > 2.5 ? 0.15 : avgGoals > 1.5 ? 0.1 : 0.05;
  };

  // 计算概率矩阵
  const calculateProbabilityMatrix = (
    homeExpected: number,
    awayExpected: number,
    rho: number
  ) => {
    let homeWin = 0;
    let draw = 0;
    let awayWin = 0;

    // 考虑0-4个进球的情况
    for (let i = 0; i <= 4; i++) {
      for (let j = 0; j <= 4; j++) {
        const prob = calculateAdjustedProbability(i, j, homeExpected, awayExpected, rho);
        if (i > j) homeWin += prob;
        else if (i === j) draw += prob;
        else awayWin += prob;
      }
    }

    // 归一化
    const total = homeWin + draw + awayWin;
    return {
      homeWin: (homeWin / total) * 100,
      draw: (draw / total) * 100,
      awayWin: (awayWin / total) * 100
    };
  };

  // 计算调整后的概率
  const calculateAdjustedProbability = (
    homeGoals: number,
    awayGoals: number,
    homeExpected: number,
    awayExpected: number,
    rho: number
  ): number => {
    const poissonHome = Math.exp(-homeExpected) * Math.pow(homeExpected, homeGoals) / factorial(homeGoals);
    const poissonAway = Math.exp(-awayExpected) * Math.pow(awayExpected, awayGoals) / factorial(awayGoals);
    
    // 考虑进球相关性的调整
    const adjustment = (homeGoals === 0 && awayGoals === 0) ? (1 + rho) :
                      (homeGoals === 0 && awayGoals === 1) ? (1 - rho) :
                      (homeGoals === 1 && awayGoals === 0) ? (1 - rho) :
                      (homeGoals === 1 && awayGoals === 1) ? (1 + rho) : 1;

    return poissonHome * poissonAway * adjustment;
  };

  const renderDataInputSection = (title: string, data: MatchData, onChange: (field: keyof MatchData, value: number) => void) => (
    <Grow in={true} timeout={800}>
      <StyledCard>
        <CardContent>
          <Typography variant="h6" gutterBottom color="primary">
            {title}
          </Typography>
          <DataRow>
            <AnimatedTextField
              label="胜场"
              type="number"
              size="small"
              value={data.wins}
              onChange={(e) => onChange('wins', Number(e.target.value))}
            />
            <AnimatedTextField
              label="平场"
              type="number"
              size="small"
              value={data.draws}
              onChange={(e) => onChange('draws', Number(e.target.value))}
            />
            <AnimatedTextField
              label="负场"
              type="number"
              size="small"
              value={data.losses}
              onChange={(e) => onChange('losses', Number(e.target.value))}
            />
            <AnimatedTextField
              label="进球"
              type="number"
              size="small"
              value={data.goalsFor}
              onChange={(e) => onChange('goalsFor', Number(e.target.value))}
            />
            <AnimatedTextField
              label="失球"
              type="number"
              size="small"
              value={data.goalsAgainst}
              onChange={(e) => onChange('goalsAgainst', Number(e.target.value))}
            />
          </DataRow>
        </CardContent>
      </StyledCard>
    </Grow>
  );

  const handleHomeTeamChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setHomeTeam(prevState => ({
      ...prevState,
      name: e.target.value
    }));
  };

  const handleAwayTeamChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setAwayTeam(prevState => ({
      ...prevState,
      name: e.target.value
    }));
  };

  // Add handicap analysis function
  const analyzeHandicap = () => {
    const { value: handicap, odds } = asianHandicap;
    let handicapPrediction = '';
    let handicapConfidence = 0;
    let handicapExplanation = '';

    // 计算赔率差
    const oddsGap = Math.abs(odds.home - odds.away);
    
    // 计算让球和赔率的相关性
    if (handicap > 0) { // 主队让球
      if (odds.home > odds.away + 0.02) { // 主队高水
        if (handicap >= 1) {
          handicapPrediction = '客队加';
          handicapConfidence = Math.min(90, 65 + oddsGap * 25);
          handicapExplanation = '主队让球较多且高水，客队优势明显';
        } else {
          handicapPrediction = '客队加';
          handicapConfidence = Math.min(85, 60 + oddsGap * 20);
          handicapExplanation = '主队让球且高水，客队优势较大';
        }
      } else if (odds.away > odds.home + 0.02) { // 主队低水
        if (handicap >= 1) {
          handicapPrediction = '观望';
          handicapConfidence = 50;
          handicapExplanation = '主队让球较多但低水，盘口存在矛盾';
        } else {
          handicapPrediction = '主队让';
          handicapConfidence = Math.min(80, 55 + oddsGap * 20);
          handicapExplanation = '主队让球但低水，可能存在主队优势';
        }
      } else { // 水位接近
        handicapPrediction = '观望';
        handicapConfidence = 50;
        handicapExplanation = '主队让球但水位接近，建议观望';
      }
    } else if (handicap < 0) { // 主队受让
      if (odds.home < odds.away - 0.02) { // 主队低水
        if (handicap <= -1) {
          handicapPrediction = '主队受让';
          handicapConfidence = Math.min(90, 65 + oddsGap * 25);
          handicapExplanation = '主队受让较多且低水，主队优势明显';
        } else {
          handicapPrediction = '主队受让';
          handicapConfidence = Math.min(85, 60 + oddsGap * 20);
          handicapExplanation = '主队受让且低水，主队优势较大';
        }
      } else if (odds.away < odds.home - 0.02) { // 主队高水
        if (handicap <= -1) {
          handicapPrediction = '观望';
          handicapConfidence = 50;
          handicapExplanation = '主队受让较多但高水，盘口存在矛盾';
        } else {
          handicapPrediction = '客队让';
          handicapConfidence = Math.min(80, 55 + oddsGap * 20);
          handicapExplanation = '主队受让但高水，可能存在客队优势';
        }
      } else { // 水位接近
        handicapPrediction = '观望';
        handicapConfidence = 50;
        handicapExplanation = '主队受让但水位接近，建议观望';
      }
    } else { // 平手盘
      if (odds.home > odds.away + 0.02) { // 主队高水
        handicapPrediction = '客队';
        handicapConfidence = Math.min(80, 55 + oddsGap * 20);
        handicapExplanation = '平手盘主队高水，客队优势较大';
      } else if (odds.away > odds.home + 0.02) { // 主队低水
        handicapPrediction = '主队';
        handicapConfidence = Math.min(80, 55 + oddsGap * 20);
        handicapExplanation = '平手盘主队低水，主队优势较大';
      } else { // 水位接近
        handicapPrediction = '观望';
        handicapConfidence = 50;
        handicapExplanation = '平手盘水位接近，建议观望';
      }
    }

    setHandicapAnalysis({
      recommendation: handicapPrediction,
      confidence: handicapConfidence,
      explanation: handicapExplanation
    });

    return {
      prediction: handicapPrediction,
      confidence: handicapConfidence,
      explanation: handicapExplanation
    };
  };

  useEffect(() => {
    if (asianHandicap.odds.home > 0 && asianHandicap.odds.away > 0) {
      analyzeHandicap();
    }
  }, [asianHandicap]);

  // Modify the renderAsianHandicapSection function
  const renderAsianHandicapSection = () => (
    <Grow in={true} timeout={800}>
      <StyledCard>
        <CardContent>
          <Typography variant="h6" gutterBottom color="primary">
            亚盘数据
          </Typography>
          <HandicapContainer>
            <HandicapRow>
              <HandicapTextField
                label="主队水位"
                type="number"
                value={asianHandicap.odds.home}
                onChange={(e) => setAsianHandicap(prev => ({
                  ...prev,
                  odds: {
                    ...prev.odds,
                    home: Number(e.target.value)
                  }
                }))}
                InputProps={{
                  inputProps: { 
                    step: 0.01,
                    min: 0.1,
                    max: 10
                  }
                }}
              />
              <HandicapSelect>
                <InputLabel>让球</InputLabel>
                <Select
                  value={asianHandicap.value}
                  label="让球"
                  onChange={(e) => setAsianHandicap(prev => ({
                    ...prev,
                    value: Number(e.target.value)
                  }))}
                >
                  {handicapOptions.map((option) => (
                    <MenuItem key={option.value} value={option.value}>
                      {option.label}
                    </MenuItem>
                  ))}
                </Select>
              </HandicapSelect>
              <HandicapTextField
                label="客队水位"
                type="number"
                value={asianHandicap.odds.away}
                onChange={(e) => setAsianHandicap(prev => ({
                  ...prev,
                  odds: {
                    ...prev.odds,
                    away: Number(e.target.value)
                  }
                }))}
                InputProps={{
                  inputProps: { 
                    step: 0.01,
                    min: 0.1,
                    max: 10
                  }
                }}
              />
            </HandicapRow>
            
            {handicapAnalysis.recommendation && (
              <HandicapAnalysis>
                <Typography variant="subtitle1" gutterBottom>
                  亚盘分析
                </Typography>
                <Typography variant="body1" gutterBottom>
                  建议: {handicapAnalysis.recommendation} 
                  （置信度: {handicapAnalysis.confidence}%）
                </Typography>
                <Typography variant="body2" color="textSecondary">
                  {handicapAnalysis.explanation}
                </Typography>
              </HandicapAnalysis>
            )}
          </HandicapContainer>
        </CardContent>
      </StyledCard>
    </Grow>
  );

  return (
    <Container maxWidth="lg">
      <Box sx={{ py: 4 }}>
        <Zoom in={true} timeout={1000}>
          <Typography 
            variant="h3" 
            component="h1" 
            gutterBottom 
            align="center"
            sx={{ 
              fontWeight: 'bold',
              background: 'linear-gradient(45deg, #1976d2 30%, #2196f3 90%)',
              WebkitBackgroundClip: 'text',
              WebkitTextFillColor: 'transparent',
              mb: 4,
              textShadow: '2px 2px 4px rgba(0,0,0,0.1)',
            }}
          >
            足球比赛预测系统
          </Typography>
        </Zoom>

        <Grid container spacing={3}>
          <Grid item xs={12}>
            {renderAsianHandicapSection()}
          </Grid>
          <Grid item xs={12}>
            {renderDataInputSection(
              '交锋历史数据（近6场）',
              homeTeam.h2h,
              (field, value) => setHomeTeam({
                ...homeTeam,
                h2h: { ...homeTeam.h2h, [field]: value }
              })
            )}
          </Grid>

          <Grid item xs={12} md={6}>
            {renderDataInputSection(
              '主队近6场数据',
              homeTeam.recent,
              (field, value) => setHomeTeam({
                ...homeTeam,
                recent: { ...homeTeam.recent, [field]: value }
              })
            )}
          </Grid>

          <Grid item xs={12} md={6}>
            {renderDataInputSection(
              '客队近6场数据',
              awayTeam.recent,
              (field, value) => setAwayTeam({
                ...awayTeam,
                recent: { ...awayTeam.recent, [field]: value }
              })
            )}
          </Grid>
        </Grid>

        <Box sx={{ mt: 4, display: 'flex', justifyContent: 'center' }}>
          <PulsingButton
            variant="contained"
            size="large"
            onClick={calculatePrediction}
            disabled={isCalculating}
            sx={{
              borderRadius: 2,
              padding: '12px 48px',
              fontSize: '1.2rem',
              background: 'linear-gradient(45deg, #1976d2 30%, #2196f3 90%)',
              boxShadow: '0 3px 5px 2px rgba(33, 150, 243, .3)',
            }}
          >
            {isCalculating ? (
              <CircularProgress size={24} color="inherit" />
            ) : (
              '计算预测结果'
            )}
          </PulsingButton>
        </Box>

        {prediction && showResults && (
          <Fade in={showResults} timeout={1000}>
            <ResultCard>
              <Typography variant="h4" align="center" gutterBottom>
                预测结果：{prediction.result}
              </Typography>
              <Typography variant="h6" align="center" gutterBottom>
                置信度：{prediction.confidence.toFixed(1)}%
              </Typography>
              <LinearProgress 
                variant="determinate" 
                value={prediction.confidence} 
                sx={{ 
                  height: 10, 
                  borderRadius: 5,
                  backgroundColor: 'rgba(255,255,255,0.2)',
                  '& .MuiLinearProgress-bar': {
                    backgroundColor: 'white',
                    transition: 'transform 2s ease-in-out',
                  }
                }} 
              />
              <Divider sx={{ my: 2, backgroundColor: 'rgba(255,255,255,0.2)' }} />
              <Grid container spacing={2}>
                {prediction.models.map((model, index) => (
                  <Grow
                    in={showResults}
                    timeout={1000 + index * 200}
                    key={index}
                  >
                    <Grid item xs={12} sm={6} md={4}>
                      {renderModelDetails(model)}
                    </Grid>
                  </Grow>
                ))}
              </Grid>
            </ResultCard>
          </Fade>
        )}
      </Box>
    </Container>
  );
};

export default App; 